<template>
  <div class="users-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button
            type="primary"
            @click="showAddDialog = true"
          >
            添加用户
          </el-button>
        </div>
      </template>
      
      <el-table :data="users" style="width: 100%">
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="roles" label="角色">
          <template #default="scope">
            {{ formatRoles(scope.row.roles) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="editUser(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deleteUser(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="showDialog"
      width="30%"
    >
      <el-form :model="userForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="userForm.username" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="密码" v-if="!isEdit">
          <el-input v-model="userForm.password" type="password" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="userForm.roles" multiple>
            <el-option
              v-for="role in availableRoles"
              :key="role"
              :label="formatRole(role)"
              :value="role"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="saveUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus' 

export default {
  setup() {
    const users = ref([])
    const showDialog = ref(false)
    const isEdit = ref(false)
    const userForm = ref({
      username: '',
      email: '',
      password: '',
      roles: []
    })

    const availableRoles = ['ROLE_USER', 'ROLE_LIBRARIAN', 'ROLE_ADMIN']

    const dialogTitle = computed(() => isEdit.value ? '编辑用户' : '添加用户')

    const loadUsers = async () => {
      try {
        const response = await axios.get('/api/users')
        users.value = response.data
      } catch (error) {
        ElMessage.error('获取用户列表失败')
      }
    }

    const editUser = (user) => {
      isEdit.value = true
      userForm.value = { ...user }
      showDialog.value = true
    }

    const saveUser = async () => {
      try {
        if (isEdit.value) {
          await axios.put(`/api/users/${userForm.value.id}`, userForm.value)
        } else {
          await axios.post('/api/users', userForm.value)
        }
        ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
        showDialog.value = false
        loadUsers()
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
      }
    }

    const deleteUser = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
          type: 'warning'
        })
        await axios.delete(`/api/users/${id}`)
        ElMessage.success('删除成功')
        loadUsers()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    const formatRoles = (roles) => {
      return roles.map(role => formatRole(role.name)).join(', ')
    }

    const formatRole = (role) => {
      return role.replace('ROLE_', '')
        .toLowerCase()
        .replace(/^\w/, c => c.toUpperCase())
    }

    return {
      users,
      showDialog,
      isEdit,
      userForm,
      availableRoles,
      dialogTitle,
      editUser,
      saveUser,
      deleteUser,
      formatRoles,
      formatRole
    }
  }
}
</script> 